from decimal import Decimal
from django.shortcuts import render
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection

from goods.models import SKU
from orders.serializers import OrderSerializers, SaveOrderSerializers


class OrdersView(APIView):
    '''展示订单商品'''

    def get(self, request):
        # 获取用户对象
        user = request.user
        # 获取redis缓存数据库中的数据 获取选中状态的sku_id
        # 建立缓存连接
        conn = get_redis_connection('cart')
        # 获取商品数量
        sku_count = conn.hgetall('cart_%s' % user.id)
        cart = {}
        for sku_id, count in sku_count.items():
            cart[int(sku_id)] = int(count)

        # 获取选中状态的sku_id
        sku_ids = conn.smembers('cart_select_%s' % user.id)
        # 根据redis中的sku_id进行商品查询
        skus = SKU.objects.filter(id__in=sku_ids)

        # 对商品对象添加属性count
        for sku in skus:
            sku.count = cart[sku.id]

        # 运费
        freight = Decimal('10.00')

        # 序列化返回
        ser = OrderSerializers({'skus': skus, 'freight': freight})

        return Response(ser.data)


class SaveOrderView(CreateAPIView):
    '''保存订单'''

    serializer_class = SaveOrderSerializers